<template>
	<picker 
		mode="multiSelector" 
		:range="dateTimeRange" 
		:value="dateTimeValue"
		@change="handleChange"
		@columnchange="handleColumnChange"
		class="datetime-picker-wrapper"
	>
		<view class="date-chip-picker">
			<text class="date-chip-text">{{ displayLabel }}</text>
			<text class="dropdown-icon">▼</text>
		</view>
	</picker>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'

// Props
const props = defineProps({
	// 初始年月日时
	modelValue: {
		type: Object,
		default: () => ({
			year: '',
			month: '',
			day: '',
			hour: ''
		})
	},
	// 默认时间偏移（天数），负数表示过去，正数表示未来
	defaultDaysOffset: {
		type: Number,
		default: 0
	}
})

// Emits
const emit = defineEmits(['update:modelValue', 'change'])

// 响应式数据
const dateTimeValue = ref([0, 0, 0, 0])
const dateTimeRange = ref([[], [], [], []])

// 计算显示标签
const displayLabel = computed(() => {
	const { year, month, day, hour } = props.modelValue
	if (!year || !month || !day || !hour) return '请选择时间'
	return `${year}/${month}/${day} ${hour}时`
})

// 初始化日期时间选择器数据
function initDateTimePickerData() {
	const now = new Date()
	const currentYear = now.getFullYear()
	
	// 生成年份数组（近5年）
	const years = []
	for (let i = currentYear - 4; i <= currentYear; i++) {
		years.push(i.toString())
	}
	
	// 生成月份数组
	const months = []
	for (let i = 1; i <= 12; i++) {
		months.push(i.toString().padStart(2, '0'))
	}
	
	// 生成日期数组（默认31天）
	const days = []
	for (let i = 1; i <= 31; i++) {
		days.push(i.toString().padStart(2, '0'))
	}
	
	// 生成小时数组
	const hours = []
	for (let i = 0; i < 24; i++) {
		hours.push(i.toString().padStart(2, '0'))
	}
	
	dateTimeRange.value = [years, months, days, hours]
	
	// 设置初始值
	if (props.modelValue.year) {
		// 如果有传入值，使用传入值
		const yearIndex = years.indexOf(props.modelValue.year)
		const monthIndex = months.indexOf(props.modelValue.month)
		const dayIndex = days.indexOf(props.modelValue.day)
		const hourIndex = hours.indexOf(props.modelValue.hour)
		
		dateTimeValue.value = [
			yearIndex >= 0 ? yearIndex : 0,
			monthIndex >= 0 ? monthIndex : 0,
			dayIndex >= 0 ? dayIndex : 0,
			hourIndex >= 0 ? hourIndex : 0
		]
	} else {
		// 否则使用当前时间（加上偏移）
		const targetDate = new Date()
		targetDate.setDate(targetDate.getDate() + props.defaultDaysOffset)
		
		const targetYear = targetDate.getFullYear()
		const targetMonth = targetDate.getMonth()
		const targetDay = targetDate.getDate()
		const targetHour = targetDate.getHours()
		
		const yearIndex = years.indexOf(targetYear.toString())
		const monthIndex = targetMonth
		const dayIndex = targetDay - 1
		const hourIndex = targetHour
		
		dateTimeValue.value = [yearIndex, monthIndex, dayIndex, hourIndex]
		
		// 触发初始值更新
		const selectedValue = {
			year: targetYear.toString(),
			month: months[monthIndex],
			day: days[dayIndex],
			hour: hours[hourIndex]
		}
		emit('update:modelValue', selectedValue)
	}
}

// 列变化处理（滚动时触发）
function handleColumnChange(e) {
	const { column, value } = e.detail
	
	// 只处理年份（column=0）或月份（column=1）的变化
	if (column === 0 || column === 1) {
		// 创建临时值数组
		const tempValues = [...dateTimeValue.value]
		tempValues[column] = value
		
		const year = dateTimeRange.value[0][tempValues[0]]
		const month = dateTimeRange.value[1][tempValues[1]]
		
		// 计算该年月的天数
		const daysInMonth = new Date(parseInt(year), parseInt(month), 0).getDate()
		const newDays = []
		for (let i = 1; i <= daysInMonth; i++) {
			newDays.push(i.toString().padStart(2, '0'))
		}
		
		// 更新日期列表
		dateTimeRange.value = [
			dateTimeRange.value[0],
			dateTimeRange.value[1],
			newDays,
			dateTimeRange.value[3]
		]
		
		// 如果当前选中的日期超出范围，调整为最后一天
		if (tempValues[2] >= daysInMonth) {
			tempValues[2] = daysInMonth - 1
			dateTimeValue.value = tempValues
		}
	}
}

// 确认选择处理
function handleChange(e) {
	const values = e.detail.value
	dateTimeValue.value = values
	
	const year = dateTimeRange.value[0][values[0]]
	const month = dateTimeRange.value[1][values[1]]
	const day = dateTimeRange.value[2][values[2]]
	const hour = dateTimeRange.value[3][values[3]]
	
	const selectedValue = { year, month, day, hour }
	
	// 更新 v-model
	emit('update:modelValue', selectedValue)
	
	// 触发 change 事件
	emit('change', selectedValue)
}

// 监听外部值变化
watch(() => props.modelValue, (newVal) => {
	if (newVal.year && newVal.month && newVal.day && newVal.hour) {
		const yearIndex = dateTimeRange.value[0].indexOf(newVal.year)
		const monthIndex = dateTimeRange.value[1].indexOf(newVal.month)
		const dayIndex = dateTimeRange.value[2].indexOf(newVal.day)
		const hourIndex = dateTimeRange.value[3].indexOf(newVal.hour)
		
		if (yearIndex >= 0 && monthIndex >= 0 && dayIndex >= 0 && hourIndex >= 0) {
			dateTimeValue.value = [yearIndex, monthIndex, dayIndex, hourIndex]
		}
	}
}, { deep: true })

onMounted(() => {
	initDateTimePickerData()
})
</script>

<style scoped>
.datetime-picker-wrapper {
	display: inline-block;
}

.date-chip-picker {
	display: inline-flex;
	align-items: center;
	gap: 8rpx;
	background: #ffffff;
	border: 1rpx solid #e9edf3;
	border-radius: 12rpx;
	padding: 10rpx 16rpx;
	white-space: nowrap;
}

.date-chip-text {
	color: #3c4353;
	font-size: 26rpx;
}

.dropdown-icon {
	color: #9aa0a6;
	font-size: 24rpx;
	margin-left: 12rpx;
}
</style>
